import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as api from '@/api'
import type { Workspace, AnalysisSession } from '../types/workspace'
import { useAnalysisStore } from './analysis'

export const useWorkspaceStore = defineStore('workspace', () => {
  // 状态
  const workspaces = ref<Workspace[]>([])
  const currentWorkspace = ref<Workspace | null>(null)
  const sessions = ref<AnalysisSession[]>([])
  const currentSession = ref<AnalysisSession | null>(null)
  const loading = ref(false)

  // 计算属性
  const hasWorkspaces = computed(() => workspaces.value.length > 0)
  const hasCurrentWorkspace = computed(() => currentWorkspace.value !== null)
  const hasSessions = computed(() => sessions.value.length > 0)

  // 工作区管理
  const loadWorkspaces = async () => {
    try {
      loading.value = true
      const data = await api.getWorkspaces()
      workspaces.value = data as unknown as Workspace[]
      
      // 如果没有当前工作区，选择第一个
      if (!currentWorkspace.value && workspaces.value.length > 0) {
        currentWorkspace.value = workspaces.value[0]
        await loadSessions()
        
        // 自动选择第一个有分析结果的会话作为当前会话
        if (sessions.value.length > 0) {
          const sessionWithAnalysis = sessions.value.find(s => s.analysis_results)
          if (sessionWithAnalysis) {
            currentSession.value = sessionWithAnalysis
          } else {
            // 如果没有有分析结果的会话，选择第一个
            currentSession.value = sessions.value[0]
          }
        }
      }
    } catch (error: any) {
      ElMessage.error(`加载工作区失败: ${error.message}`)
    } finally {
      loading.value = false
    }
  }

  const createWorkspace = async (name: string, description?: string) => {
    try {
      loading.value = true
      const workspace = await api.createWorkspace({ name, description })
      workspaces.value.unshift(workspace as unknown as Workspace)
      currentWorkspace.value = workspace as unknown as Workspace
      // 清空当前会话与会话列表
      currentSession.value = null
      sessions.value = []
      // 同步清理分析数据，避免其他页面遗留旧数据
      try {
        const analysisStore = useAnalysisStore()
        analysisStore.clearData()
      } catch (e) {
        // 忽略清理失败以避免影响主流程
      }
      ElMessage.success('工作区创建成功')
      return workspace
    } catch (error: any) {
      ElMessage.error(`创建工作区失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateWorkspace = async (workspaceId: string, data: Partial<Workspace>) => {
    try {
      loading.value = true
      const updatedWorkspace = await api.updateWorkspace(workspaceId, data)
      
      const index = workspaces.value.findIndex(w => w.id === workspaceId)
      if (index >= 0) {
        workspaces.value[index] = updatedWorkspace as unknown as Workspace
      }
      
      if (currentWorkspace.value?.id === workspaceId) {
        currentWorkspace.value = updatedWorkspace as unknown as Workspace
      }
      
      ElMessage.success('工作区更新成功')
      return updatedWorkspace
    } catch (error: any) {
      ElMessage.error(`更新工作区失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteWorkspace = async (workspaceId: string) => {
    try {
      loading.value = true
      await api.deleteWorkspace(workspaceId)
      
      workspaces.value = workspaces.value.filter(w => w.id !== workspaceId)
      
      if (currentWorkspace.value?.id === workspaceId) {
        currentWorkspace.value = workspaces.value.length > 0 ? workspaces.value[0] : null
        if (currentWorkspace.value) {
          await loadSessions()
        } else {
          sessions.value = []
        }
      }
      
      ElMessage.success('工作区删除成功')
    } catch (error: any) {
      ElMessage.error(`删除工作区失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const switchWorkspace = async (workspace: Workspace) => {
    currentWorkspace.value = workspace
    await loadSessions()
  }

  // 会话管理
  const loadSessions = async () => {
    if (!currentWorkspace.value) return
    
    try {
      loading.value = true
      const data = await api.getAnalysisSessions(currentWorkspace.value.id)
      sessions.value = data as unknown as AnalysisSession[]
    } catch (error: any) {
      ElMessage.error(`加载分析会话失败: ${error.message}`)
    } finally {
      loading.value = false
    }
  }

  const createSession = async (name: string, description?: string) => {
    if (!currentWorkspace.value) {
      throw new Error('没有选择工作区')
    }

    try {
      loading.value = true
      const session = await api.createAnalysisSession({
        workspace_id: currentWorkspace.value.id,
        name,
        description
      })
      sessions.value.unshift(session as unknown as AnalysisSession)
      currentSession.value = session as unknown as AnalysisSession
      ElMessage.success('分析会话创建成功')
      return session
    } catch (error: any) {
      ElMessage.error(`创建分析会话失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateSession = async (sessionId: string, data: Partial<AnalysisSession>) => {
    try {
      loading.value = true
      const updatedSession = await api.updateAnalysisSession(sessionId, data)
      
      const index = sessions.value.findIndex(s => s.id === sessionId)
      if (index >= 0) {
        sessions.value[index] = updatedSession as unknown as AnalysisSession
      }
      
      if (currentSession.value?.id === sessionId) {
        currentSession.value = updatedSession as unknown as AnalysisSession
      }
      
      ElMessage.success('分析会话更新成功')
      return updatedSession
    } catch (error: any) {
      ElMessage.error(`更新分析会话失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteSession = async (sessionId: string) => {
    try {
      loading.value = true
      await api.deleteAnalysisSession(sessionId)
      
      sessions.value = sessions.value.filter(s => s.id !== sessionId)
      
      if (currentSession.value?.id === sessionId) {
        currentSession.value = sessions.value.length > 0 ? sessions.value[0] : null
      }
      
      ElMessage.success('分析会话删除成功')
    } catch (error: any) {
      ElMessage.error(`删除分析会话失败: ${error.message}`)
      throw error
    } finally {
      loading.value = false
    }
  }

  const switchSession = async (session: AnalysisSession) => {
    currentSession.value = session
    
    // 自动加载会话的分析数据到analysisStore
    try {
      const analysisStore = useAnalysisStore()
      
      // 首先加载会话到后端内存，确保其他API能正常工作
      await api.loadSessionToMemory(session.id)
      
      // 然后获取分析数据到前端状态
      await analysisStore.loadAnalysisFromSession(session.id)
    } catch (error) {
      console.warn('加载会话分析数据失败:', error)
      
      // 如果新API失败，尝试使用旧的方法
      if (session.analysis_results) {
        const analysisStore = useAnalysisStore()
        analysisStore.setAnalysisFromSession(session)
      }
    }
  }

  // 初始化
  const initialize = async () => {
    await loadWorkspaces()
  }

  return {
    // 状态
    workspaces,
    currentWorkspace,
    sessions,
    currentSession,
    loading,

    // 计算属性
    hasWorkspaces,
    hasCurrentWorkspace,
    hasSessions,

    // 工作区方法
    loadWorkspaces,
    createWorkspace,
    updateWorkspace,
    deleteWorkspace,
    switchWorkspace,

    // 会话方法
    loadSessions,
    createSession,
    updateSession,
    deleteSession,
    switchSession,

    // 初始化
    initialize
  }
})
